<script setup>
import { ref, watchEffect } from 'vue'
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()

const activeIndex = ref('1')

// ✅ 根据当前路径设置高亮项
watchEffect(() => {
  const path = route.path
  if (path.startsWith('/home/dynamic')) {
    activeIndex.value = '1'
  } else if (path.startsWith('/home/article')) {
    activeIndex.value = '2'
  } else if (path.startsWith('/home/reading')) {
    activeIndex.value = '3'
  } else if (path.startsWith('/home/user')) {
    activeIndex.value = '4'
  } else {
    activeIndex.value = '1'
  }
})

const handleSelect = (key) => {
  const uid = localStorage.getItem('uid') // ✅ 获取当前用户 ID
  const routes = {
    1: '/home/dynamic',
    2: '/home/article',
    3: '/home/reading',
    4: uid ? `/home/user/${uid}` : '/login', // ✅ 跳转到自己的个人页
  }
  if (routes[key]) {
    router.push(routes[key])
  }
}

const createArticle = () => {
  const token = localStorage.getItem('token')
  if (token) {
    router.push({ path: '/creator/image-text-editor' })
  } else {
    router.push('/login')
  }
}
</script>

<template>
  <div class="sidebar">
    <div class="nav-container">
      <nav class="nav-list">
        <a
          v-for="item in [
            { index: '1', name: '动态', icon: '📢' },
            { index: '2', name: '文章', icon: '📄' },
            { index: '3', name: '阅读', icon: '📚' },
            { index: '4', name: '个人', icon: '👤' },
          ]"
          :key="item.index"
          :class="['nav-item', { active: activeIndex === item.index }]"
          @click="handleSelect(item.index)"
        >
          <i>{{ item.icon }}</i>
          <span>{{ item.name }}</span>
        </a>
      </nav>

      <button class="post-btn" @click="createArticle">
        <span>发布内容</span>
      </button>
    </div>
  </div>
</template>

<style scoped>
.sidebar {
  width: 100%;
  background: #fff;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}
.nav-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  gap: 10px;
  flex-grow: 1;
}
.nav-list {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.nav-item {
  display: flex;
  align-items: center;
  width: 100%;
  padding: 10px;
  border-radius: 6px;
  color: #333;
  cursor: pointer;
  transition: background 0.3s;
}
.nav-item i {
  margin-right: 10px;
  font-size: 18px;
}
.nav-item.active {
  background: #007bff;
  color: white;
  font-weight: bold;
}
.post-btn {
  width: 100%;
  padding: 10px;
  background: #28a745;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 16px;
}
</style>
